import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, StyleSheet, Alert, ScrollView, TouchableOpacity, Image } from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
import { useNavigation } from '@react-navigation/native';
import { get, post } from '../http/http';
import { Select } from 'teaset';
const DeviceFixScreen = ({ route }) => {
  const { classroomId } = route.params;
  const [faultTypeList, setFaultTypeList] = useState([]);
  const [typeId, setTypeId] = useState('');
  const [faultPlace, setFaultPlace] = useState('');
  const [faultMessage, setFaultMessage] = useState('');
  const [imageValue, setImageValue] = useState([]);
  const navigation = useNavigation();

  useEffect(() => {
    loadFaultTypeList();
  }, []);

  const loadFaultTypeList = async () => {
    try {
      const response = await get('member/repairType/api/selectRepairTypeList?route=member');
      const list = response.data.map(v => ({ text: v.typeName, value: v.typeId }));
      setFaultTypeList(list);
      if (list.length > 0) {
        setTypeId(list[0].value);
      }
      else {
        setTypeId('');
      }
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const selectImage = () => {
    launchImageLibrary({ mediaType: 'photo', selectionLimit: 9 }, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        setImageValue(response.assets.map(asset => asset.uri));
      }
    });
  };

  const submit = async () => {
    try {
      await post('member/userRepair/api/addRepairFront?route=member', {
        laboratoryId: classroomId,
        repairPlace: faultPlace,
        repairContent: faultMessage,
        repairType: typeId,
      });
      Alert.alert('Success', '报修成功');
      navigation.goBack();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>故障类型</Text>
        <View style={styles.pickerContainer}>

          <Select
            onSelected={(item: any, index: number) => {
              setTypeId(faultTypeList[index].value);
            }}
            value={faultTypeList.find(v => v.value === typeId)?.text}
            // pickerType={'popover'}
            getItemValue={(item: any, index: number) => item}
            items={faultTypeList.map(v => v.text)}
            style={{ flex: 1 }}
          />
        </View>
      </View>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>故障地点</Text>
        <TextInput
          style={styles.textInput}
          placeholder="请输入内容"
          value={faultPlace}
          onChangeText={setFaultPlace}
          multiline
        />
      </View>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>故障描述</Text>
        <TextInput
          style={styles.textInput}
          placeholder="请输入内容"
          value={faultMessage}
          onChangeText={setFaultMessage}
          multiline
        />
      </View>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>选择图片</Text>
        <TouchableOpacity onPress={selectImage} style={styles.imagePicker}>
          <Text style={styles.imagePickerText}>选择图片</Text>
        </TouchableOpacity>
        <View style={styles.imageContainer}>
          {imageValue.map((uri, index) => (
            <Image key={index} source={{ uri }} style={styles.image} />
          ))}
        </View>
      </View>
      <View style={styles.buttonContainer}>
        <Button title="提交" onPress={submit} color="#4EB894" />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F7F8F8',
    padding: 10,
  },
  section: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  pickerContainer: {
    backgroundColor: 'white',
    padding: 10,
    borderRadius: 5,
  },
  pickerItem: {
    paddingVertical: 10,
  },
  pickerItemText: {
    fontSize: 14,
  },
  pickerItemSelected: {
    fontSize: 14,
    color: '#4EB894',
    fontWeight: 'bold',
  },
  textInput: {
    backgroundColor: 'white',
    padding: 10,
    borderRadius: 5,
    height: 100,
    textAlignVertical: 'top',
  },
  imagePicker: {
    backgroundColor: 'white',
    padding: 10,
    borderRadius: 5,
    alignItems: 'center',
  },
  imagePickerText: {
    color: '#4EB894',
    fontWeight: 'bold',
  },
  imageContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 10,
  },
  image: {
    width: 100,
    height: 100,
    marginRight: 10,
    marginBottom: 10,
  },
  buttonContainer: {
    marginTop: 20,
  },
});

export default DeviceFixScreen;
